<template>
  <view class="logistics-page">
    <!-- 物流公司信息 -->
    <view class="logistics-header">
      <view class="logistics-company">
        <image
          :src="logisticsinfo.logo"
          mode="aspectFit"
          class="company-logo"
        ></image>
        <text class="company-name">{{ logisticsinfo.company }}</text>
        <text class="tracking-number">{{ logisticsinfo.info.nu }}</text>
      </view>
      <view class="action-buttons">
        <text class="copy-btn" @click="copyTrackingNumber">复制</text>
        <text class="call-btn" @click="callExpress">打电话</text>
      </view>
    </view>

    <!-- 物流状态时间线 -->
    <view class="logistics-timeline">
      <view class="timeline-line"></view>
      <view
        class="timeline-item"
        v-for="(item, index) in logisticsData"
        :key="index"
        :class="{ active: index === 0 }"
      >
        <view class="timeline-dot">
          <view class="dot" :class="{ active: index === 0 }"></view>
        </view>
        <view class="timeline-content">
          <view
            class="timeline-time"
            :style="{ color: index === 0 ? '#000' : '#999' }"
            ><view class="timeline-status" :class="{ active: index === 0 }" v-if="index === 0">{{
              getLogisticsStatusText(logisticsinfo.info.state)
            }}</view
            >{{ item.time }}</view
          >
          <view class="timeline-detail">
            <template v-for="(segment, segmentIndex) in parseTextWithPhone(item.context)" :key="segmentIndex">
              <text v-if="!segment.isPhone">{{ segment.text }}</text>
              <text v-else class="phone-text" @tap="makePhoneCallFromText(segment.text)">{{ segment.text }}</text>
            </template>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import orderApi from "@/request/order";
export default {
  data() {
    return {
      orderId: "",
      logisticsData: [],
      logisticsinfo: {
        info:{
          data:[]
        }
      },
    };
  },
  onLoad(options) {
    // 获取传递的参数，如订单号等
    if (options.orderId) {
      this.orderId = options.orderId;
      this.getLogisticsData();
    }
  },
  methods: {
    // 物流状态 -1-暂无物流信息 0在途，1揽收，2疑难，3签收，4退签，5派件，14拒签。待收货返回，其他状态时返回null.
    getLogisticsStatusText(status) {
      switch (status) {
        case '-1':
          return "暂无物流信息";
        case '0':
          return "运输中";
        case '1':
          return "已揽收";
        case '3':
          return "已签收";
        case '4':
          return "退签";
        case '5':
          return "派件中";
        case '14':
          return "拒签";
        default:
          return '';
      }
    },
    copyTrackingNumber() {
      uni.setClipboardData({
        data: this.orderId,
        success: () => {
          uni.showToast({
            title: "运单号已复制",
            icon: "success",
          });
        },
      });
    },
    callExpress() {
      uni.makePhoneCall({
        phoneNumber: this.logisticsinfo.tel,
      });
    },
    getLogisticsData() {
      orderApi.getLogisticsInfo({ orderId: this.orderId }).then((res) => {
        console.log(res);
        this.logisticsData = res.info.data;
        this.logisticsinfo = res;
      });
    },
    parseTextWithPhone(text) {
      if (!text) return [{ text: '', isPhone: false }];
      
      // 电话号码正则表达式：手机号（11位）、固话（带区号）、客服热线等
      const phoneRegex = /(\b1[3-9]\d{9}\b)|(\b\d{3,4}[-\s]?\d{7,8}\b)|(\b[9]\d{4}\b)|(\b400[-\s]?\d{3}[-\s]?\d{4}\b)/g;
      
      const segments = [];
      let lastIndex = 0;
      let match;
      
      while ((match = phoneRegex.exec(text)) !== null) {
        // 添加电话号码前的普通文本
        if (match.index > lastIndex) {
          segments.push({
            text: text.substring(lastIndex, match.index),
            isPhone: false
          });
        }
        
        // 添加电话号码
        segments.push({
          text: match[0],
          isPhone: true
        });
        
        lastIndex = match.index + match[0].length;
      }
      
      // 添加剩余的普通文本
      if (lastIndex < text.length) {
        segments.push({
          text: text.substring(lastIndex),
          isPhone: false
        });
      }
      
      // 如果没有匹配到电话号码，返回整个文本
      if (segments.length === 0) {
        return [{
          text: text,
          isPhone: false
        }];
      }
      
      return segments;
    },
    makePhoneCallFromText(phoneNumber) {
      // 清理电话号码格式
      const cleanPhone = phoneNumber.replace(/[-\s]/g, '');
      
      uni.makePhoneCall({
        phoneNumber: cleanPhone,
        success: () => {
          console.log('拨打电话成功');
        },
        fail: (err) => {
          console.log('拨打电话失败', err);
          uni.showToast({
            title: '拨打电话失败',
            icon: 'none'
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.logistics-page {
  background-color: #fff;
  min-height: 100vh;
  padding-top: 20rpx;
}

.logistics-header {
  background-color: #ffffff;
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logistics-company {
  display: flex;
  align-items: center;
  flex: 1;

  .company-logo {
    width: 60rpx;
    height: 60rpx;
    margin-right: 20rpx;
    border-radius: 50%;
  }

  .company-name {
    font-size: 26rpx;
    color: #666;
    margin-right: 20rpx;
  }

  .tracking-number {
    font-size: 26rpx;
    color: #666;
  }
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 46rpx;

  .copy-btn,
  .call-btn {
    font-size: 26rpx;
    color: #666;
  }

  .copy-btn::after {
    content: "";
    position: absolute;
    right: -22rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 1rpx;
    height: 24rpx;
    background-color: #999;
  }

  .copy-btn {
    position: relative;
  }
}

.logistics-timeline {
  background-color: #ffffff;
  padding: 0 30rpx;
  position: relative;
}

.timeline-line {
  position: absolute;
  left: 40rpx;
  top: 30rpx;
  bottom: 30rpx;
  width: 2rpx;
  background-color: #e0e0e0;
  z-index: 1;
}

.timeline-item {
  display: flex;
  padding: 0;
  position: relative;
  z-index: 2;
  .timeline-content {
    margin-bottom: 30rpx;
  }

  &.active {
    .timeline-content .timeline-status {
      color: #000;
      font-weight: 600;
      display: inline-block;
      margin-right: 21rpx;
    }
  }

  &:last-of-type {
    &::after {
      content: "";
      position: absolute;
      left: 0;
      top: 20rpx;
      width: 20rpx;
      height: 100%;
      background-color: #fff;
    }
  }
}

.timeline-dot {
  position: absolute;
  display: flex;
  align-items: flex-start;
  top: 10rpx;

  .dot {
    width: 20rpx;
    height: 20rpx;
    border-radius: 50%;
    background-color: #fff;
    border: 1.5rpx solid #999999;
    z-index: 3;

    &.active {
      top: 0rpx;
      background-color: #000;
    }
  }
}

.timeline-content {
  flex: 1;
  margin-left: 60rpx;

  .timeline-status {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 8rpx;

    &.active {
      color: #1890ff;
      font-weight: 600;
    }
  }

  .timeline-time {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 8rpx;
  }

  .timeline-detail {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
    
    .phone-text {
      color: #1890ff;
      text-decoration: underline;
      font-weight: 500;
    }
  }
}
</style>
